// @ts-nocheck
import React, { useRef, useEffect, useState } from "react";
import { json, useNavigate, useSearchParams } from "react-router-dom";
import { Form, Input, Button, Toast, DotLoading, Dialog } from "antd-mobile";
import md5 from "js-md5";
import { login, submit, submit1, update, userAuthInfo, autoLogin, register } from "./servece";
import { formdataify } from "@/utils/Axios";
import { filterPage } from "@/utils";
import {
  setToken,
  setAccessToken,
  setRefreshToken,
  setCurrentUser,
  setKepperToken,
} from "@/utils/authority";
import "./index.less";
import {
  EyeInvisibleOutline,
  EyeOutline,
  CheckCircleFill,
} from "antd-mobile-icons";
const Login: React.FC = () => {
  let userMsg = { username: "", password: "" };
  const orLogin = localStorage.getItem("nameAndPas");

  if (orLogin) {
    userMsg = JSON.parse(orLogin);
  }

  const remPas = useRef(null); //获取dom节点
  const [form] = Form.useForm();
  const [itemVisble, setItemVisble] = useState(false);
  const [passwordVisible, setPasswordVisible] = useState(false);
  const [passwordVisible1, setPasswordVisible1] = useState(false);
  const [passwordVisible2, setPasswordVisible2] = useState(false);
  const [loading, setLoading] = useState(true);


  const [searchParams] = useSearchParams();
  const [pageLoading, setPageLoading] = useState(true);
  const userid = searchParams.get('userId');
  const route = searchParams.get('route');
  // console.log(userid, route)

  const navigate = useNavigate();
  useEffect(() => {
    if (userid) {
      toPageLogin()
    } else {
      setPageLoading(false)
    }
  }, [])

  const handleCancel = () => {
    window.history.back()
  };

  const goRegister = async () => {
    const params = {
      userid
    };
    try {
      const { data } = await register(params);
      if (data?.access_token) {
        const {
          token_type,
          access_token,
          refresh_token,
          expires_in = 0,
          ...users
        } = data || {};
        localStorage.setItem("users", JSON.stringify({ ...users }));

        setToken(`${token_type} ${access_token}`);
        setRefreshToken(refresh_token || "");
        setAccessToken(access_token);
        setCurrentUser(data);

        login().then((res1) => {
          if (res1.code == 200) {
            userAuthInfo().then((infoData) => {
              if (infoData.code == 200) {
                localStorage.setItem("authFlag", infoData.data.authFlag);
              }
            });
            localStorage.setItem("user_info", JSON.stringify(res1));
            window.LoginUserInfo = JSON.stringify(res1);
            navigate('/signSuccess', {state:route})
          } else {
            Toast.show({
              icon: "fail",
              content: res1.msg,
            });
          }
        });
      } else {
        Toast.show({
          icon: "fail",
          content: "注册失败",
        });
        setPageLoading(false)
      }
    } catch {
      Toast.show({
        icon: "fail",
        content: "注册失败",
      });
      setPageLoading(false)
    }
  };
  const toPageLogin = async () => {
    const params = {
      userid
    };
    try {
      const { data, msg, code } = await autoLogin(params);

      if (data?.access_token) {
        const {
          token_type,
          access_token,
          refresh_token,
          expires_in = 0,
          ...users
        } = data || {};
        localStorage.setItem("users", JSON.stringify({ ...users }));

        setToken(`${token_type} ${access_token}`);
        setRefreshToken(refresh_token || "");
        setAccessToken(access_token);
        setCurrentUser(data);

        login().then((res1) => {
          if (res1.code == 200) {
            userAuthInfo().then((infoData) => {
              if (infoData.code == 200) {
                localStorage.setItem("authFlag", infoData.data.authFlag);
              }
            });
            localStorage.setItem("user_info", JSON.stringify(res1));
            window.LoginUserInfo = JSON.stringify(res1);

            navigate(filterPage(route))

          } else {
            Toast.show({
              icon: "fail",
              content: res1.msg,
            });
          }
        });
      } else if (code == 401) {
        Dialog.show({
          content: '您未注册社区账户，是否注册',
          closeOnAction: true,
          actions: [
            [
              {
                key: 'cancel',
                text: '取消',
                onClick: handleCancel,
              },
              {
                key: 'signin',
                text: '注册',
                bold: true,
                onClick: goRegister,
              },
            ],
          ],
        })
      } else {
        Toast.show({
          icon: "fail",
          content: msg,
        });
        setPageLoading(false)
      }
    } catch {
      Toast.show({
        icon: "fail",
        content: "用户Id解析失败",
      });
      setPageLoading(false)

    }
  };

  const onFinish = (values: any) => {
    setLoading(false);
    const isLogin = remPas.current.checked;
    if (isLogin) {
      localStorage.setItem(
        "nameAndPas",
        JSON.stringify({
          username: values.username,
          password: values.password,
        })
      );
    } else {
      localStorage.removeItem("nameAndPas");
    }
    const value = {
      ...values,
      password: md5(values.password),
      tenantId: "000000",
      scope: "all",
      grant_type: "password",
      type: "account",
    };
    const values1 = {
      ...values,
      tenantId: "000000",
      scope: "all",
      grant_type: "password",
      type: "account",
    };

    submit(formdataify(value))
      .then((data) => {
        // console.log(data);
        if (data?.data?.access_token) {
          const {
            token_type,
            access_token,
            refresh_token,
            expires_in = 0,
            ...users
          } = data?.data || {};
          localStorage.setItem("users", JSON.stringify({ ...users }));
          const time = new Date().getTime();
          setToken(`${token_type} ${access_token}`);
          setRefreshToken(refresh_token || "");
          setAccessToken(access_token);
          setCurrentUser(data);

          submit1(values1).then((res) => {
            if (res.data.code == 200) {
              const tokenArr = document.cookie.split("=");
              setKepperToken(tokenArr[1]);

              Toast.show({
                icon: "success",
                content: res.data.msg,
              });
              login().then((res1) => {
                if (res1.code == 200) {
                  userAuthInfo().then((infoData) => {
                    if (infoData.code == 200) {
                      localStorage.setItem("authFlag", infoData.data.authFlag);
                    }
                  });
                  localStorage.setItem("user_info", JSON.stringify(res1));
                  window.LoginUserInfo = JSON.stringify(res1);

                  navigate("/");
                } else {
                  Toast.show({
                    icon: "fail",
                    content: res1.msg,
                  });
                }
              });
            } else if (
              res.data.code == 400 &&
              res.data.msg == "请修改初始密码"
            ) {
              setItemVisble(true);
            } else {
              Toast.show({
                icon: "fail",
                content: res.data.msg,
              });
            }
          });
        } else {
          Toast.show({
            icon: "fail",
            content: "用户名或密码错误",
          });
          // throw new Error(data.msg)
        }
      })
      .catch((err) => {
        // Toast.show({
        //     icon: 'fail',
        //     content: err.toString(),
        // })
      })
      .finally((all) => {
        setTimeout(() => {
          setLoading(true);
        }, 2000);
      });
  };
  const onSub = (value) => {
    update(value)
      .then((res) => {
        if (res.data.code == 200) {
          setItemVisble(false);
        } else {
          Toast.show({
            icon: "fail",
            content: res.response?.data.msg,
          });
        }
      })
      .catch((error) => { });
  };
  return (
    <div>
      {
        pageLoading ?
          <div style={{ width: '100%', display: 'flex', justifyContent: 'center', paddingTop: '3rem' }}>
            <DotLoading color='primary' />
          </div>
          :
          <>
            <h1 style={{ textAlign: "center", marginTop: "40px" }}>
              智慧广安运营中心·智慧社区
            </h1>
            <div style={{ padding: "20px" }}>
              {itemVisble ? (
                <Form
                  name="basic"
                  onFinish={onSub}
                  form={form}
                  footer={
                    <div style={{ display: "flex", justifyContent: "center" }}>
                      <Button
                        // block
                        type="submit"
                        color="primary"
                        size="large"
                        className="botton"
                      >
                        提交
                      </Button>
                      <Button
                        color="primary"
                        size="large"
                        className="botton"
                        style={{ marginLeft: "20px" }}
                        onClick={() => setItemVisble(false)}
                      >
                        取消{" "}
                      </Button>
                    </div>
                  }
                >
                  <div className="password">
                    <Form.Item
                      label="旧密码"
                      name="oldPassword"
                      rules={[{ required: true, message: "请输入旧密码!" }]}
                    >
                      <Input
                        type={passwordVisible2 ? "text" : "password"}
                        placeholder="请输入旧密码"
                        suffix={
                          <img
                            style={{ cursor: "pointer" }}
                            onClick={() =>
                              setPasswordVisible2((prevState) => !prevState)
                            }
                            src={passwordVisible2 ? "./icon3.png" : "./icon4.png"}
                          />
                        }
                      />
                    </Form.Item>
                    <div className="eye">
                      {!passwordVisible2 ? (
                        <EyeInvisibleOutline
                          onClick={() => setPasswordVisible2(true)}
                        />
                      ) : (
                        <EyeOutline onClick={() => setPasswordVisible2(false)} />
                      )}
                    </div>
                  </div>

                  <div className="password">
                    <Form.Item
                      label="新密码"
                      name="newPassword"
                      rules={[
                        {
                          required: true,
                          pattern:
                            /(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[\W_]).{8,16}/,
                          message:
                            "请输入8~16位字母大小写+数宇+特殊符号 示例: Jy159@371",
                        },
                      ]}
                    >
                      <Input
                        type={passwordVisible1 ? "text" : "password"}
                        placeholder="请输入新密码"
                        suffix={
                          <img
                            style={{ cursor: "pointer" }}
                            onClick={() =>
                              setPasswordVisible1((prevState) => !prevState)
                            }
                            src={passwordVisible1 ? "./icon3.png" : "./icon4.png"}
                          />
                        }
                      />
                    </Form.Item>
                    <div className="eye">
                      {!passwordVisible1 ? (
                        <EyeInvisibleOutline
                          onClick={() => setPasswordVisible1(true)}
                        />
                      ) : (
                        <EyeOutline onClick={() => setPasswordVisible1(false)} />
                      )}
                    </div>
                  </div>
                  <div className="password">
                    <Form.Item
                      label="确认密码"
                      name="confirmPassword"
                      rules={[
                        {
                          required: true,
                          pattern:
                            /(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[\W_]).{8,16}/,
                          message:
                            "请输入8~16位字母大小写+数宇+特殊符号 示例: Jy159@371",
                        },
                        ({ getFieldValue }) => ({
                          validator(_, value) {
                            if (!value || getFieldValue("newPassword") === value) {
                              return Promise.resolve();
                            }
                            return Promise.reject(new Error("两次密码输入不一致"));
                          },
                        }),
                      ]}
                    >
                      <Input
                        type={passwordVisible ? "text" : "password"}
                        placeholder="请输入确认密码"
                        suffix={
                          <img
                            style={{ cursor: "pointer" }}
                            onClick={() =>
                              setPasswordVisible((prevState) => !prevState)
                            }
                            src={passwordVisible ? "./icon3.png" : "./icon4.png"}
                          />
                        }
                      />
                    </Form.Item>
                    <div className="eye">
                      {!passwordVisible ? (
                        <EyeInvisibleOutline
                          onClick={() => setPasswordVisible(true)}
                        />
                      ) : (
                        <EyeOutline onClick={() => setPasswordVisible(false)} />
                      )}
                    </div>
                  </div>
                </Form>
              ) : (
                <Form
                  initialValues={{
                    username: userMsg.username,
                    password: userMsg.password,
                  }}
                  form={form}
                  onFinish={(e) => {
                    if (loading) onFinish(e);
                  }}
                  footer={
                    <Button
                      block
                      type="submit"
                      color="primary"
                      size="large"
                      // disabled={loading}
                      style={{ margin: "0 auto" }}
                    >
                      登录
                    </Button>
                  }
                >
                  <Form.Item
                    name="username"
                    rules={[{ required: true, message: "账号不能为空" }]}
                  >
                    <Input placeholder="请输入账号" />
                  </Form.Item>
                  <Form.Item
                    name="password"
                    rules={[{ required: true, message: "请输入密码" }]}
                  >
                    <Input
                      placeholder="请输入6-8位用户密码"
                      clearable
                      type="password"
                    />
                  </Form.Item>
                </Form>
              )}
              {!itemVisble && (
                <div className="remberBox">
                  <input
                    type="checkbox"
                    value={1}
                    id="remberPas"
                    style={{ marginRight: "10px" }}
                    ref={remPas}
                  />
                  <label htmlFor="remberPas">记住密码</label>{" "}
                </div>
              )}

              {itemVisble && (
                <div style={{ fontSize: "2rem" }}>
                  <div>温馨提示：</div>
                  <div> 为保障账号安全，请及时修改初始密码。</div>
                  <div>
                    {" "}
                    新密码修改完成后将会自动退出登录，你需要使用新密码重新登录。
                  </div>
                  <div> 忘记密码请联系管理员！</div>
                </div>
              )}
            </div>
          </>
      }


    </div>
  );
};

export default Login;
